
// 导入axios
import axios from 'axios'
import router from '../router'
import { commonAPI } from './api';

// 使用element-ui Message做消息提醒
import { Message } from 'element-ui';

/*是否有请求正在刷新token*/
let isRefreshing = false;
/*被挂起的请求数组*/
let subscribers = []

/*push所有请求到数组中*/
function addSubscriber(callback) {
  subscribers.push(callback)
}
/*刷新请求（refreshSubscribers数组中的请求得到新的token之后会自执行）*/
function onAccessTokenFetched(token) {
  subscribers.forEach((callback) => {
    callback(token);
  })
  subscribers = [];
}


function refreshTokenRequst() {
  //console.log(3333)
  let token = localStorage.getItem('refreshToken');
  //let token = 'bearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJzeXNfdXNlciIsImhvc3QiOiIwOjA6MDowOjA6MDowOjEiLCJpZCI6IjEiLCJleHAiOjE1OTIxOTQwMDR9.-4JLvAhBZ9Nwtr8aLqobYWZqnkan3rm86lbRxg1QROg';

  commonAPI.refreshToken({ token })
    .then((response) => {
      console.log(response);
      localStorage.setItem('token', response.data.token);
      onAccessTokenFetched(response.data.token);
      isRefreshing = false;
    }).catch(err => {
      console.log(err)
    });
}

let token = ''

axios.defaults.withCredentials = false;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头

//1. 创建新的axios实例，
const service = axios.create({
  // 公共接口--这里注意后面会讲
  baseURL: '/api/',
  // 超时时间 单位是ms，这里设置了3s的超时时间
  timeout: 3 * 1000
})

// 2.请求拦截器
service.interceptors.request.use(config => {
  //发请求前做的一些处理，数据转化，配置请求头，设置token,设置loading等
  token = localStorage.getItem('token');//从localstroage中获取token
  if (token) {
    config.headers.common['Authorization'] = 'bearer' + token
  }
  return config
}, error => {
  Promise.reject(error)
})


/*3.响应拦截器*/
service.interceptors.response.use(
  response => {
    console.log(response)
    // 对响应数据做点什么
    if (response.data.code != 0 && response.data.code != 7) {
      Message.error(response.data.msg)
      if (response.data.code === 401) {
        // 如果当前路由不是login
        // 那么去请求新 token
        console.log(response.data.code)
        if (router.currentRoute.name !== 'login') {
          if (!isRefreshing) {
            console.log(222)
            refreshTokenRequst()
          }
          isRefreshing = true;
          // 这个Promise函数很关键
          const retryOriginalRequest = new Promise((resolve) => {
            addSubscriber((token) => {
              response.config.headers.Authorization = 'bearer' + token
              resolve(axios.request(response.config))
            })
          });
          return retryOriginalRequest;
        }
      }
      else if (response.data.code === 402 || response.data.code === 403 || response.data.code === 404) {
        router.push('/login')
      } else {
        return Promise.reject(response.data)
      }
    } else {
      return Promise.resolve(response.data)
    }
  },
  error => {
    // 对响应错误做点什么
    return Promise.reject(error.response)
  }
)

//4.导入文件
export default service
